<template>
  <div class="flex flex-row">
    <h3 class="text-4xl" ref="counterRef">0</h3>
    <h4 class="flex flex-col justify-end">{{ unit }}</h4>
  </div>
</template>

<script setup lang="ts">
import { CountUp } from "countup.js";

const props = defineProps<{
  num: number;
  /**
   * 数量单位
   */
  unit: string;
}>();

const counterRef = ref<HTMLHeadingElement>();
const { num } = toRefs(props);

let countUpInstance: CountUp | null = null;
const observer = buildIntersectionObserver(updateNum);
function updateNum(entries: IntersectionObserverEntry[]) {
  if (
    countUpInstance &&
    counterRef.value &&
    targetDomIsCrossRoot(entries, counterRef.value)
  ) {
    console.log("执行");
    countUpInstance.update(num.value);
    if (observer) {
      observer.disconnect();
    }
  }
}

watch(
  num,
  (newNum) => {
    countUpInstance && countUpInstance.update(newNum);
  },
  { immediate: true }
);

onMounted(() => {
  const dom = counterRef.value;
  if (!dom) return;
  countUpInstance = new CountUp(dom, num.value);
  addObserve(dom, observer);
});

onUnmounted(() => {
  const dom = counterRef.value;
  if (!dom) return;
  removeObserve(dom, observer, true);
});
</script>

<style scoped></style>
